import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { LoadingBar } from 'view-ui-plus'
import Layout from '@/layout/index/index.vue'

// 静态路由
export const constantRoutes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login/index.vue'),
        meta: { title: '登录' }
    },
    {
        path: '/',
        component: Layout,
        redirect: '/setting/users',
        children: [
            {
                path: 'setting',
                name: 'setting',
                meta: { title: '系统管理' },
                redirect: '/setting/users',
                children: [
                    {
                        path: 'users',
                        component: () => import('@/views/setting/users/index.vue'),
                        meta: { title: '用户管理' }
                    },
                    {
                        path: 'menus',
                        component: () => import('@/views/setting/menus/index.vue'),
                        meta: { title: '菜单管理' }
                    }
                ]
            }
        ]
    },
    {
        path: '/home',
        component: () => import('@/views/home/index.vue'),
        meta: {
            title: '首页'
        }
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: constantRoutes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    LoadingBar.start()
    const userStore = useUserStore()
    const token = userStore.token
    const isLoginPage = to.path === '/login'

    // 已登录状态访问登录页，跳转首页
    if (isLoginPage && token) {
        return next('/')
    }

    // 未登录状态访问非登录页，跳转登录页
    if (!isLoginPage && !token) {
        return next('/login')
    }
    // console.log('token', token)
    // 已登录但还没有菜单权限
    if (!isLoginPage && token && !userStore.menus.length) {
        try {
            // 获取用户菜单
            const menus = await userStore.getMenus()
            // 生成动态路由
            const routes = await userStore.generateRoutes(menus)
            // 添加路由
            routes.forEach((route) => {
                router.addRoute(route)
            })
            // 重新导航到目标页面
            next({ ...to, replace: true })
        } catch (error) {
            console.error('获取菜单失败:', error)
            userStore.logout()
            next('/login')
        }
        return
    }

    next()
})

router.afterEach(() => {
    LoadingBar.finish()
})

// 路由错误处理
router.onError(() => {
    LoadingBar.error()
})

export default router
